import qs from "qs";
import Axios from "axios";
import deepCopy from 'deepcopy/umd/deepcopy.min'
// 设置每个请求独立key
function setRequestKey(config) {
    let {data, method, url, params} = deepCopy(config)
    if (data && isJsonStr(data)) {
        data = JSON.parse(data)
    } else if (Object.prototype.toString.call(data) === '[object FormData]') {
        // formData格式转为对象
        const objData = {}
        data.forEach((item, key) => {
            objData[key] = item
        })
        params = objData
    }
    return [method, url, qs.stringify(params), qs.stringify(data)].join('&')
}
// 判断是否json对象
function isJsonStr(str) {
    if (typeof str == 'string') {
        try {
            let obj = JSON.parse(str);
            if (typeof obj === 'object' && obj) {
                return true;
            } else {
                return false;
            }
        } catch (e) {
            return false;
        }
    }
}

// 键值对存储请求对象
const mapRequest = new Map()
// 添加重复请求
function addRequestPending(config) {
    const key = setRequestKey(config)
    if (mapRequest.has(key)) {
        config.cancelToken = new Axios.CancelToken(cancel => {
            // 取消重复请求
            cancel(config.url + ' 重复请求');
        });
    } else {
        config.cancelToken = config.cancelToken || new Axios.CancelToken(cancel => {
            mapRequest.set(key, cancel);
        });
    }
}

// 清空所有请求map元素
function clearRequestClear() {
    mapRequest.clear()
}

// 请求响应 删除对象已经添加的请求key
function removeRequestPending(config) {
    const key = setRequestKey(config)
    if (mapRequest.has(key)) {
        const cancelToken = mapRequest.get(key);
        cancelToken(key);
        mapRequest.delete(key);
    }
}

export {
    setRequestKey,
    addRequestPending,
    removeRequestPending,
    clearRequestClear
}
